package com.example.wwlco.testdemo;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wwlco.testdemo.download.LoadFileModel;
import com.example.wwlco.testdemo.download.Md5Tool;
import com.example.wwlco.testdemo.filepicker.FolderActivity;
import com.example.wwlco.testdemo.library.fileviewer.FileViewer;
import com.example.wwlco.testdemo.permission.MPermission;
import com.google.zxing.activity.CaptureActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    private Button button;
    private Button checkFile;
    private TextView showText;

    private String mUrl = "http://partners.adobe.com/public/developer/en/xml/AdobeXMLFormsSamples.pdf";
    private EditText docUrl;
    private Button showDoc;
    public static final int REQUEST_QR_CODE = 888;
    String pptUrl = "http://repo.changxianggu.com/upload/press/e95b0201907111033299472.pptx";
    String wordUrl = "http://repo.changxianggu.com/upload/press/46b1b201907111051164032.doc";
    String excelUrl = "http://repo.changxianggu.com/upload/press/eac17201907111106312259.xls";
    //  String pdfUrl = "http://file.dakawengu.com/file/2018-05-29/20180527-tianfeng.pdf";
    String pdfUrl = "http://repo.changxianggu.com/upload/press/6ac8d201907111335138180.pdf";
    private Button copyPptBtn;
    private Button copyPdfBtn;
    private Button copyWordBtn;
    private Button copyExcelBtn;
    private Button scanFileBtn;
    private Button QRcodeScanBtn;
    private TextView scanResultText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestBasicPermission();


        button = ((Button) findViewById(R.id.dowwnLoad));
        checkFile = ((Button) findViewById(R.id.checkFile));
        showText = ((TextView) findViewById(R.id.showText));
        docUrl = ((EditText) findViewById(R.id.docUrl));
        showDoc = ((Button) findViewById(R.id.showDoc));
        scanFileBtn = ((Button) findViewById(R.id.scanFile));
        QRcodeScanBtn = ((Button) findViewById(R.id.QRcodeScan));
        scanResultText = ((TextView) findViewById(R.id.scanResult));
        docUrl.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mUrl = s.toString();
            }
        });
        checkFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkFileIsExits();
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startDown(mUrl);
            }
        });
        showDoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showThisDoc();
            }
        });

        copyPptBtn = ((Button) findViewById(R.id.copayPpt));
        copyPdfBtn = ((Button) findViewById(R.id.copyPdf));
        copyWordBtn = ((Button) findViewById(R.id.copyWord));
        copyExcelBtn = ((Button) findViewById(R.id.copyExcel));

        copyPptBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager cmb = (ClipboardManager) MainActivity.this .getSystemService(Context.CLIPBOARD_SERVICE);
                cmb.setText(pptUrl);
                String result = cmb.getText().toString();
                if (result.equals(pptUrl)) {
                    Toast.makeText(MainActivity.this, "pptUrl复制成功", Toast.LENGTH_LONG).show();
                }
                docUrl.setText("");
            }
        });

        copyPdfBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager cmb = (ClipboardManager) MainActivity.this .getSystemService(Context.CLIPBOARD_SERVICE);
                cmb.setText(pdfUrl);
                String result = cmb.getText().toString();
                if (result.equals(pdfUrl)) {
                    Toast.makeText(MainActivity.this, "pdfUrl复制成功", Toast.LENGTH_LONG).show();
                }
                docUrl.setText("");
            }
        });

        copyWordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager cmb = (ClipboardManager) MainActivity.this .getSystemService(Context.CLIPBOARD_SERVICE);
                cmb.setText(wordUrl);
                String result = cmb.getText().toString();
                if (result.equals(wordUrl)) {
                    Toast.makeText(MainActivity.this, "wordUrl复制成功", Toast.LENGTH_LONG).show();
                }
                docUrl.setText("");
            }
        });

        copyExcelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ClipboardManager cmb = (ClipboardManager) MainActivity.this .getSystemService(Context.CLIPBOARD_SERVICE);
                cmb.setText(excelUrl);
                String result = cmb.getText().toString();
                if (result.equals(excelUrl)) {
                    Toast.makeText(MainActivity.this, "excelUrl复制成功", Toast.LENGTH_LONG).show();
                }
                docUrl.setText("");

            }
        });
        scanFileBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, FolderActivity.class);
                startActivity(intent);
            }
        });
        QRcodeScanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_QR_CODE);
            }
        });

    }

    private void showThisDoc() {
        File cacheFile = getCacheFile(mUrl);
        if (cacheFile.exists()) {
            if (cacheFile.length() <= 0) {
                cacheFile.delete();
                return;
            }else {

                FileViewer.viewFile(this, cacheFile.toString());
                //FileViewer.viewPDFWithMuPDFByPath(this, cacheFile.toString());
            }
        }else {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 基本权限管理
     */

    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA
    };

    private void requestBasicPermission() {
        MPermission.with(MainActivity.this)
                .setRequestCode(1001)
                .permissions(BASIC_PERMISSIONS)
                .request();
    }



    private void checkFileIsExits() {

        File cacheFile = getCacheFile(mUrl);
        if (cacheFile.exists()) {
            if (cacheFile.length() <= 0) {
                cacheFile.delete();
                return;
            }else {
                showText.setText("文件已经存在，下载路径为" + cacheFile.toString());
                Log.d("filePath", cacheFile.toString());
                Toast.makeText(this, "文件已经存在", Toast.LENGTH_SHORT).show();
            }
        }else {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
        }

    }

    private void startDown(final String url) {

        final ProgressDialog pd = new ProgressDialog(this);
        pd.setMessage("正在下载...");
        pd.setProgress(0);
        pd.show();
        LoadFileModel.loadPdfFile(url, new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                boolean flag;
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    ResponseBody responseBody = response.body();
                    is = responseBody.byteStream();
                    long total = responseBody.contentLength();

                    File file1 = getCacheDir(url);
                    if (!file1.exists()) {
                        file1.mkdirs();
                    }

                    //fileN : /storage/emulated/0/pdf/kauibao20170821040512.pdf
                    File fileN = getCacheFile(url);//new File(getCacheDir(url), getFileName(url))

                    if (!fileN.exists()) {
                        boolean mkdir = fileN.createNewFile();
                    }
                    fos = new FileOutputStream(fileN);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        pd.setProgress(progress);
                    }
                    fos.flush();
                    //2.ACache记录文件的有效期
                    pd.dismiss();
                    showText.setText("文件已经下载了，下载路径为" + fileN.toString());
                } catch (Exception e) {

                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                File file = getCacheFile(url);
                if (!file.exists()) {
                    file.delete();
                }
            }
        });
    }

    /***
     * 获取缓存目录
     *
     * @param url
     * @return
     */
    public File getCacheDir(String url) {

        return new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/document/");

    }

    /***
     * 绝对路径获取缓存文件
     *
     * @param url
     * @return
     */
    private File getCacheFile(String url) {
        File cacheFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/document/"
                + getFileName(url));
        return cacheFile;
    }

    /***
     * 根据链接获取文件名（带类型的），具有唯一性
     *
     * @param url
     * @return
     */
    private String getFileName(String url) {
        String fileName = Md5Tool.hashKey(url) + "." + getFileType(url);
        return fileName;
    }

    /***
     * 获取文件类型
     *
     * @param paramString
     * @return
     */
    private String getFileType(String paramString) {
        String str = "";

        if (TextUtils.isEmpty(paramString)) {
            return str;
        }
        int i = paramString.lastIndexOf('.');
        if (i <= -1) {
            return str;
        }
        str = paramString.substring(i + 1);
        return str;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_QR_CODE) {
            //    String result = data.getStringExtra("result");
            try {
                String result = data.getStringExtra(CaptureActivity.SCAN_QRCODE_RESULT);
                if (result != null) {
                    scanResultText.setText("扫描结果" + result);
                    Toast.makeText(this, "" + result, Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
